package com.yww.leetcode.queue;

import com.yww.datastructure.queue.ArrayQueue2;
import com.yww.datastructure.queue.LinkedListQueue;
import com.yww.datastructure.queue.Queue;
import com.yww.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yww
 * @description 102. 二叉树的层序遍历
 * @since 2024/2/4 18:31
 */
public class LevelOrder102 {
    // 给你二叉树的根节点 root ，返回其节点值的 层序遍历 。
    // （即逐层地，从左到右访问所有节点）。
    // 解：使用队列完成层序遍历
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);
        int c1 = 1;
        while (!queue.isEmpty()) {
            int c2 = 0;
            List<Integer> level = new ArrayList<>();
            res.add(level);
            for (int i = 0; i < c1; i++) {
                TreeNode poll = queue.poll();
                level.add(poll.val);
                if (poll.left != null) {
                    c2++;
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    c2++;
                    queue.offer(poll.right);
                }
            }
            c1 = c2;
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                new TreeNode(2,
                        new TreeNode(4, null, null),
                        new TreeNode(5, null, null)),
                new TreeNode(3,
                        new TreeNode(6, null, null),
                        new TreeNode(7, null, null)));

        Queue<TreeNode> queue = new ArrayQueue2<>(10);
        queue.offer(root);
        int c1 = 1;
        while (!queue.isEmpty()) {
            int c2 = 0;
            for (int i = 0; i < c1; i++) {
                TreeNode poll = queue.poll();
                System.out.print(poll);
                if (poll.left != null) {
                    c2++;
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    c2++;
                    queue.offer(poll.right);
                }
            }
            System.out.println();
            c1 = c2;
        }

        System.out.println(new LevelOrder102().levelOrder(root));
    }
}
